using System;
using System.DirectoryServices;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;

namespace OutlookAddIn_Auto_Grouping_Inbox
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            AutoGroupingInbox();
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        private void AutoGroupingInbox()
        {
            Outlook.MAPIFolder mailbox_folder = (Outlook.MAPIFolder)this.Application.GetNamespace("MAPI").GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox).Parent;
            try
            {
                mailbox_folder.Folders.Add(System.Environment.UserName, Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }
            Outlook.MAPIFolder jarvis_folder = (Outlook.MAPIFolder)mailbox_folder.Folders[System.Environment.UserName];

            Outlook.Items inbox_items = this.Application.GetNamespace("MAPI").GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox).Items;

            DirectoryEntry rootEntry = new DirectoryEntry("LDAP://dc=phoenix,dc=com");
            DirectorySearcher searcher = new DirectorySearcher(rootEntry);

            for (int i = 1; i <= inbox_items.Count; i++)
            {
                Outlook.MailItem mi = (Outlook.MailItem)(inbox_items[i]);
                string strSender = mi.SenderName;
                //MessageBox.Show(strSender);

                searcher.Filter = string.Format("(name={0})", strSender);
                searcher.PropertiesToLoad.Add("department");
                searcher.PropertiesToLoad.Add("l");
                searcher.SearchScope = SearchScope.Subtree;
                SearchResultCollection results = searcher.FindAll();

                if (results.Count > 0)
                {
                    // find more than one ...
                    if (results.Count > 1)
                    {
                        MessageBox.Show("more than one result found : " + strSender);
                    }
                    else // only found one
                    {
                        SearchResult result = results[0];

                        // location
                        string location = string.Empty;
                        if (result.Properties["l"] != null && result.Properties["l"].Count > 0)
                        {
                            location = result.Properties["l"][0].ToString();
                            //MessageBox.Show(location);
                        }
                        // make location folder
                        try
                        {
                            if (location != string.Empty)
                            {
                                jarvis_folder.Folders.Add(location, Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
                            }
                            else
                            {
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            /*
                            MessageBox.Show("add folder error : " + location);
                            MessageBox.Show(ex.ToString());
                             */
                        }
                        Outlook.MAPIFolder location_folder = (Outlook.MAPIFolder)jarvis_folder.Folders[location];

                        // department
                        string department = string.Empty;
                        if (result.Properties["department"] != null && result.Properties["department"].Count > 0)
                        {
                            department = result.Properties["department"][0].ToString();
                            //MessageBox.Show(department);
                        }
                        // make department folder
                        try
                        {
                            if (department != string.Empty)
                            {
                                location_folder.Folders.Add(department, Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
                            }
                            else
                            {
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            /*
                            MessageBox.Show("add folder error : " + department);
                            MessageBox.Show(ex.ToString());
                             */
                        }
                        Outlook.MAPIFolder department_folder = (Outlook.MAPIFolder)location_folder.Folders[department];

                        // move mi to department_folder
                        Outlook.MailItem moveMail = mi;
                        try
                        {
                            moveMail.Move(department_folder);
                        }
                        catch (Exception ex)
                        {
                            /*
                            MessageBox.Show("move mail error");
                            MessageBox.Show(ex.ToString());
                             */
                        }
                    }
                }
            }
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}
